from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.models import OAuthQQUser
from oauth.utils import check_open_id
from users.models import User


class QQAuthUserSerializer(serializers.Serializer):
    # 手机号,密码,短信验证码,以及处理之后的openid
    mobile = serializers.RegexField(max_length=11, label="手机号", regex=r"^1[3-9]\d{9}$")
    password = serializers.CharField(required=True, label="密码", max_length=20, min_length=8)
    sms_code = serializers.CharField(label="短信验证码")
    access_token = serializers.CharField(label="操作凭证")

    def validate(self, attrs):

        token = attrs.get("access_token")
        mobile = attrs.get("mobile")
        password = attrs.get("password")
        sms_code = attrs.get("sms_code")

        # 首先校验的是access_token
        openid = check_open_id(token)
        if openid is None:
            raise serializers.ValidationError("openid可能被篡改了")

        attrs["openid"] = openid

        # 判断用户是否存在
        user = User.objects.get(mobile=mobile)
        if user is None:
            """如果用户不存在的话,就要创建用户"""
            pass
        attrs["user"] = user

        # 短信验证码  获取到redis里面的sms_code,然后跟用户输入的进行一个对比
        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get("sms_%s" % mobile)
        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError("验证码不一致")

        # 校验密码  根据mobile取出密码,然后根据用户输入的数据进行一个比较
        # aa = user.check_password(password)
        # print(aa)
        if not user.check_password(password):
            raise serializers.ValidationError("密码不一致")
        return attrs

    # 通过流传递,用户输入的手机号,密码,短信验证码和token,后台接收data,
    # 通过data --> attrs --> validated_data 需要得到
    def create(self, validated_data):

        user = validated_data["user"]

        if user is None:
            user = User.objects.create(
                username=validated_data["mobile"],
                password = validated_data["password"],
                mobile = validated_data["mobile"]
            )

        qquser = OAuthQQUser.objects.create(
            openid = validated_data["openid"],
            user = user
        )
        return qquser


















